/**
 * @filename DriverController.java
 */
package com.liupf.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.upload.UploadFile;
import com.jfinal.util.PathUtil;
import com.liupf.common.utils.Constants;
import com.liupf.common.utils.MD5Util;
import com.liupf.common.utils.SmsUtil;
import com.liupf.common.utils.TypeConstant;
import com.liupf.domain.BUserEnroll;
import com.liupf.domain.Driver;
import com.liupf.domain.Tel;

/**
 * @description 代驾员管理
 * @author shevliu
 * @email shevliu@gmail.com Jul 28, 2012 5:00:46 PM
 */
public class DriverController extends Controller {
	private Log log = LogFactory.getLog(this.getClass());

	public void index() {
		String job_number = getPara("job_number");
		String realName = getPara("real_name");
		String cellPhone = getPara("cell_phone");
		String status = getPara("status");
		String balance = getPara("balance");
		String sameCompany = getPara("sameCompany");
		String createBySelf = getPara("createBySelf");
		int sysUserId = (Integer) getSession().getAttribute("userId");
		
		//操作员自己所属品牌
		String company=(String) getSession().getAttribute("company");
		String syscity=(String) getSession().getAttribute("syscity");
		String userRole = (String)getSession().getAttribute("userRole");
			
		StringBuffer from = new StringBuffer();
		from.append(" from b_user a ");
		from.append(" LEFT JOIN tel_company tc ON tc.company = a.license_num ");
		from.append("left join (");
		from.append("select b_user_id,count(*) as finishNum from order_detail where  order_state = 4 group by b_user_id ");
		from.append(" ) b on a.id = b.b_user_id left join ( ");
		from.append("select b_user_id,count(*) as order_count from order_detail group by b_user_id ");
		from.append(" ) d on a.id = d.b_user_id left join ( ");
		from.append("select b_user_id,sum(totalmoney) as sum_money from order_detail where  order_state = 4 group by b_user_id ");
		from.append(" ) e on a.id = e.b_user_id left join ( ");
		from.append("select b_user_id,count(*) as cancelNum from order_detail where  order_state in (8,9,10,11,12,13) group by b_user_id ");
		from.append(") c on a.id = c.b_user_id where 1=1 ");
		
		if(Constants.ROLE_BRAND_MANAGER.equals(userRole) || Constants.ROLE_MIDDLE_MANAGER.equals(userRole)){
			//from.append(" and license_num like '" + company + "%'");
			/*if(StringUtils.isNotBlank(sameCompany)){
				from.append(" and license_num in (select company from tel_company where city='"+syscity+"')");
			}else{*/
				from.append(" and license_num = '" + company + "'");
		//	}
		}
		
		if(StringUtils.isNotBlank(balance)){
			from.append(" and a.balance < 200");
		}
		if(StringUtils.isNotBlank(createBySelf)){
			from.append(" and a.create_user_id ="+sysUserId);
		}
		if (StringUtils.isNotBlank(job_number)) {
			from.append(" and job_number='" + job_number.toUpperCase() + "'");
			setAttr("jobNumber", job_number);
		}
		if (StringUtils.isNotBlank(realName)) {
			from.append(" and name like'%" + realName + "%'");
			setAttr("name", realName);
		}
		if (StringUtils.isNotBlank(cellPhone)) {
			from.append(" and phone='" + cellPhone + "'");
			setAttr("phone", cellPhone);
		}
		if (StringUtils.isNotBlank(status)) {
			from.append(" and status='" + status + "'");
			setAttr("status", status);
		}
		from.append(" order by job_number,balance desc");
		
		Page<Driver> page = Driver.dao.paginate(getParaToInt(0, 1), 10,
				"select  a.*,b.*,d.*,e.*,c.*,tc.companyname,tc.commissiontype,tc.fixedmoney,tc.proportion comproportion ", from.toString());
		setAttr("page", page);
		setAttr("balance",balance);
		setAttr("sameCompany",sameCompany);
		setAttr("createBySelf",createBySelf);
		
		int pageIndex = getParaToInt(0, 1);
		setSessionAttr("driverIndex", pageIndex);
		render("driver_index.ftl");
	}

	public void exportXls() {
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet();
		HSSFRow row = sheet.createRow((short) 0);
		row.createCell(0).setCellValue("工作状态");
		row.createCell(1).setCellValue("冻结状态");
		row.createCell(2).setCellValue("工号");
		row.createCell(3).setCellValue("真实姓名");
		row.createCell(4).setCellValue("手机号码");
		row.createCell(5).setCellValue("性别");
		row.createCell(6).setCellValue("年龄");
		row.createCell(7).setCellValue("驾照");
		row.createCell(8).setCellValue("驾龄");
		row.createCell(9).setCellValue("驾照号码");
		row.createCell(10).setCellValue("籍贯");
		row.createCell(11).setCellValue("账户余额");
		row.createCell(12).setCellValue("佣金抽取比例");

		String job_number = getPara("job_number");
		String realName = getPara("real_name");
		String cellPhone = getPara("cell_phone");
		StringBuffer from = new StringBuffer();
		from.append("select * from b_user where 1=1 ");
		if (StringUtils.isNotBlank(job_number)) {
			from.append(" and job_number='" + job_number.toUpperCase() + "'");
		}
		if (StringUtils.isNotBlank(realName)) {
			from.append(" and name='" + realName + "'");
		}
		if (StringUtils.isNotBlank(cellPhone)) {
			from.append(" and phone='" + cellPhone + "'");
		}
		String company=(String) getSession().getAttribute("company");
		
		String userRole = (String)getSession().getAttribute("userRole");
		if(Constants.ROLE_BRAND_MANAGER.equals(userRole) || Constants.ROLE_MIDDLE_MANAGER.equals(userRole)){
			from.append(" and license_num='"+company+"'");
		}
		/*if(!"admin".equals(company)){
			from.append(" and license_num='"+company+"'");
		}*/
		from.append(" order by id desc");
		List<Record> driverList = Db.find(from.toString());
		for (int i = 0; i < driverList.size(); i++) {
			HSSFRow r = sheet.createRow(i + 1);
			Record record = driverList.get(i);
			int status = record.getInt("status");
			if(status == 0) {
				r.createCell(0).setCellValue("空闲");
			} else if(status == 1){
				r.createCell(0).setCellValue("待客");
			} else if(status == 2){
				r.createCell(0).setCellValue("代驾中");
			} else if(status == 3){
				r.createCell(0).setCellValue("休息");
			} else if(status == 4){
				r.createCell(0).setCellValue("备用");
			} else if(status == 5){
				r.createCell(0).setCellValue("离职");
			} else {
				r.createCell(0).setCellValue("其他");
			}
			int canuse = record.getInt("canuse");
			if(canuse == 0) {
				r.createCell(1).setCellValue("已冻结");
			} else {
				r.createCell(1).setCellValue("正常");
			}
			r.createCell(2).setCellValue(record.getStr("job_number"));
			r.createCell(3).setCellValue(record.getStr("name"));
			r.createCell(4).setCellValue(record.getStr("phone"));
			int sex = record.getInt("sex");
			if(sex == 0) {
				r.createCell(5).setCellValue("男");
			} else if(sex == 1){
				r.createCell(5).setCellValue("女");
			} else {
				r.createCell(5).setCellValue("未知");
			}
			int age = (record.getInt("age") == null ? 0 : record.getInt("age"));
			r.createCell(6).setCellValue(age);
			String driver_license = (record.getStr("driver_license") == null ? "" : record.getStr("driver_license"));
			r.createCell(7).setCellValue(driver_license);
			int driver_age = (record.getInt("driver_age") == null ? 0 : record.getInt("driver_age"));
			r.createCell(8).setCellValue(driver_age);
			
			String license_num = (record.getStr("license_num") == null ? "" : record.getStr("license_num"));
			r.createCell(9).setCellValue(license_num);
			String hometown = (record.getStr("hometown") == null ? "" : record.getStr("hometown"));
			r.createCell(10).setCellValue(hometown);
			
			BigDecimal balance = (record.getBigDecimal("balance") == null ? new BigDecimal(0) : record.getBigDecimal("balance"));
			r.createCell(11).setCellValue(balance.toPlainString());
			
			int proportion = (record.getInt("proportion") == null ? 0 : record.getInt("proportion"));
			r.createCell(12).setCellValue(proportion + "%");
		}
		PathUtil.getWebRootPath();
		String fileName = PathUtil.getWebRootPath() + "/excel/driver.xls";
		File f = new File(fileName);
		log.debug("file path:" + f.getAbsolutePath());
		FileOutputStream fOut;
		try {
			fOut = new FileOutputStream(fileName);
			workbook.write(fOut);
			fOut.flush();
			fOut.close();
		} catch (Exception e) {
			throw new RuntimeException("导出excel失败，请稍后再试", e);
		}
		renderFile(f);
	}

	public void add() {
		render("driver_add.ftl");
	}

	@Before(Tx.class)
	public void save() {
		try {
			UploadFile file = getFile("driver.head");
			UploadFile idCardImgFile = getFile("driver.id_card_img");
			UploadFile driverLicenseImgFile = getFile("driver.driver_license_img");
			Driver driver = getModel(Driver.class);
			String password = driver.getStr("pwd");
			String id_card=driver.getStr("id_card");
			String phone=driver.getStr("phone");
			String job_number=driver.getStr("job_number");
			String pwd=driver.getStr("pwd");
			String name=driver.getStr("name");
			String[] flags=getParaValues("post");
			String flag=StringUtils.join(flags, ";"); 
			
			if(id_card==null || "".equals(id_card.trim()))
			{
				throw new RuntimeException("身份证不能为空");
			}
			if(phone==null || "".equals(phone.trim()))
			{
				throw new RuntimeException("手机不能为空");
			}
			if(job_number==null || "".equals(job_number.trim()))
			{
				throw new RuntimeException("工号不能为空");
			}
			if(pwd==null || "".equals(pwd.trim()))
			{
				throw new RuntimeException("密码不能为空");
			}
			if(name==null || "".equals(name.trim()))
			{
				throw new RuntimeException("密码不能为空");
			}
			
			Record rec = Db.findFirst("select id from b_user where id_card= ?",id_card);
			if(rec!=null)
			{
				throw new RuntimeException("该身份证已被注册过了");
			}
			driver.put("pwd", MD5Util.MD5(password));
			String jobNumber = driver.getStr("job_number");
			log.debug("jobNumber:" + jobNumber);
			driver.put("job_number", jobNumber.toUpperCase());
			if (file == null) {
				driver.put("head", null);
			} else {
				driver.put("head", file.getFile().getName());
			}
			if (idCardImgFile == null) {
				driver.put("id_card_img", null);
			} else {
				driver.put("id_card_img", idCardImgFile.getFile().getName());
			}
			if (driverLicenseImgFile == null) {
				driver.put("driver_license_img", null);
			} else {
				driver.put("driver_license_img", driverLicenseImgFile.getFile().getName());
			}
			driver.put("status", 3);
			driver.put("proportion", 30);
			driver.put("post", flag);
			int sysUserId = (Integer) getSession().getAttribute("userId");
			
			driver.put("create_user_id", sysUserId);
			driver.save();
			
			String company = (String) getSession().getAttribute("company");
			String companyname = (String) getSession().getAttribute("myCompanyName");
			String userName = (String) getSession().getAttribute("userName");
			int driverId = driver.get("id");
			
			Db.update("insert into operator_log(sys_user_id,b_user_id,log_type,remarks,company,companyname,sys_user_name,create_time) values(?,?,?,?,?,?,?,?)",
					sysUserId,driverId,TypeConstant.OperatorType.DRIVER_ADD.name(),
					TypeConstant.OperatorType.DRIVER_ADD.getTypeName(),company,companyname,userName,new Date());
			
			//String content = "亲爱的"+userName+"您好，欢迎加入"+companyname+"代驾，账号:"+phone+"工号:"+jobNumber+"，密码:"+password+"。";
			String content = "欢迎你加入老兵（"+companyname+"），您的登录账号："+phone+"，初密始密码："+password+"，请尽快上线赚钱吧！";
			if(TypeConstant.admin.endsWith(company)){
				SmsUtil.sendMessage(phone,content,company);
				
				/*String insertMessage = "insert into tel_company_message(TEL,MESSAGE,COMPANY,CREATE_TIME) values(?,?,?,?)";
				Db.update(insertMessage,phone,content,company,new java.sql.Date(Calendar.getInstance().getTime().getTime()));*/
			}else{
				Calendar calendar = Calendar.getInstance();
				calendar.set(Calendar.DAY_OF_MONTH, 1);
				calendar.set(Calendar.HOUR_OF_DAY, 0);
				calendar.set(Calendar.MINUTE, 0);
				calendar.set(Calendar.SECOND, 0);
				calendar.set(Calendar.MILLISECOND, 0);
				
				Calendar calendar1 = Calendar.getInstance();    
				calendar1.set(Calendar.DAY_OF_MONTH, calendar1.getActualMaximum(Calendar.DAY_OF_MONTH));
				calendar1.set(Calendar.HOUR_OF_DAY, 23);
				calendar1.set(Calendar.MINUTE, 59);
				calendar1.set(Calendar.SECOND, 0);
				calendar1.set(Calendar.MILLISECOND, 999);
				
				//String messageCountSql = "select count(*) from tel_company_message where company=? and create_time>? and create_time<=?";
				//Long count = Db.queryFirst(messageCountSql, company, calendar.getTime(), calendar1.getTime());
				
				//String companySql = "select * from tel_company where company=?";
				//Tel tel = Tel.dao.findFirst(companySql, company);
				//int messageNum = (tel.get("message_num") == null ? 0:tel.getInt("message_num"));
				//if(count < messageNum){
					SmsUtil.sendMessage(phone,content,company);
					//String insertMessage = "insert into tel_company_message(TEL,MESSAGE,COMPANY,CREATE_TIME) values(?,?,?,?)";
					//Db.update(insertMessage,phone,content,company,new java.sql.Date(Calendar.getInstance().getTime().getTime()));
				//}
			}
			
			redirect("/driver");
		} catch (Exception e) {
			e.printStackTrace();
			if(e.getMessage()==null)
			throw new RuntimeException("添加代驾员失败，请检查填写内容是否符合要求");
			else
				throw new RuntimeException(e.getMessage());
		}
	}

	public void edit() {
		setAttr("driver", Driver.dao.findById(getParaToInt()));
		render("driver_edit.ftl");
	}
	
	public void delete(){
		Integer id = getParaToInt();
		Driver.dao.deleteById(id);
		renderText("1");
		//redirect("/driver/");
	}

	@Before(Tx.class)
	public void update() {
		// driver.update();
		UploadFile file = getFile("driver.head");
		UploadFile idCardImgFile = getFile("driver.id_card_img");
		UploadFile driverLicenseImgFile = getFile("driver.driver_license_img");
		
		int id = getParaToInt("driver.id");
		
		String job_number = getPara("driver.job_number");
		String name = getPara("driver.name");
		String phone = getPara("driver.phone");
		//String mac = getPara("driver.mac");
		String id_card = getPara("driver.id_card");
		String hometown = getPara("driver.hometown");
		Integer age = getParaToInt("driver.age");
		Integer driver_age = getParaToInt("driver.driver_age");
		String driver_license = getPara("driver.driver_license");
		String license_num = getPara("driver.license_num");
		Integer sex = getParaToInt("driver.sex");
		String password = getPara("password");
		String bank_no = getPara("driver.bank_no");
		
		String level = getPara("driver.level");
		String point = getPara("driver.point");
		if("".equals(point) || point == null){
			point = "0";
		}
		
		String[] flags=getParaValues("post");
		String flag=StringUtils.join(flags, ";");
		Driver driver = getModel(Driver.class);
		driver.put("job_number", job_number);
		driver.put("name", name);
		driver.put("phone", phone);
		driver.put("id_card", id_card);
		driver.put("hometown", hometown);
		driver.put("age", age);
		driver.put("hometown", hometown);
		driver.put("driver_age", driver_age);
		driver.put("driver_license", driver_license);
		driver.put("license_num", license_num);
		driver.put("sex", sex);
		driver.put("bank_no", bank_no);
		driver.put("level", level);
		driver.put("point", point);
		if(file != null){
			driver.set("head", file.getFile().getName());
		}
		if(idCardImgFile != null){
			driver.set("id_card_img", idCardImgFile.getFile().getName());
		}
		if(driverLicenseImgFile != null){
			driver.set("driver_license_img", driverLicenseImgFile.getFile().getName());
		}
		driver.set("post", flag);
		driver.update();
		/*if (file != null) {
			Db.update("update b_user set name=?,phone=?,mac=?,id_card=?,hometown=?,age=?,driver_age=?,driver_license=?,license_num=?,sex=?,head=?,bank_no=?,level=?,point=?,job_number=?, id_card_img=?, driver_license_img=? where id=?",
					  name, phone, mac, id_card, hometown, age,
					  driver_age, driver_license, license_num,sex, file.getFile().getName(),bank_no,level,point,job_number, 
					  idCardImgFile.getFile().getName(), driverLicenseImgFile.getFile().getName(), id);
		} else {
			Db.update("update b_user set name=?,phone=?,mac=?,id_card=?,hometown=?,age=?,driver_age=?,driver_license=?,license_num=?,sex=?,bank_no=?,level=?,point=?,job_number=?, id_card_img=?, driver_license_img=? where id=?",
					   name, phone, mac, id_card, hometown, age,
					   driver_age, driver_license,license_num,sex,bank_no,level,point,job_number, idCardImgFile.getFile().getName(), driverLicenseImgFile.getFile().getName(), id);
		}*/
		if(StringUtils.isNotBlank(password)){
			String md5PWD = MD5Util.MD5(password);
			Db.update("update b_user set pwd = ? where id=?"  , md5PWD , id);
			
			String content = "亲爱的"+name+"您的账号:"+phone+"的密码已被管理员修改，新密码:"+password+"。赶快用新密码登录试试进来代驾吧！";
			SmsUtil.sendMessage(phone,content,license_num);
			
			//String insertMessage = "insert into tel_company_message(TEL,MESSAGE,COMPANY,CREATE_TIME) values(?,?,?,?)";
			//Db.update(insertMessage,phone,content,license_num,new java.sql.Date(Calendar.getInstance().getTime().getTime()));
		}
		Integer driverIndex = getSessionAttr("driverIndex");
		if(driverIndex == null){
			driverIndex = 0;
		}
		
		String company = (String) getSession().getAttribute("company");
		String companyname = (String) getSession().getAttribute("myCompanyName");
		String userName = (String) getSession().getAttribute("userName");
		int sysUserId = (Integer) getSession().getAttribute("userId");
		
		Db.update("insert into operator_log(sys_user_id,b_user_id,log_type,remarks,company,companyname,sys_user_name,create_time) values(?,?,?,?,?,?,?,?)",
				sysUserId,id,TypeConstant.OperatorType.DRIVER_UPDATE.name(),
				TypeConstant.OperatorType.DRIVER_UPDATE.getTypeName(),company,companyname,userName,new Date());
		
		redirect("/driver/"+driverIndex);
	}

	/**
	 *
	 * @description 冻结账户
	 * @author shevliu
	 * @email shevliu@gmail.com Jul 28, 2012 6:09:25 PM
	 */
	public void frozen() {
		int id = getParaToInt(0);
		setAttr("id", id);
		render("driver_frozen.ftl");
	}

	/**
	 *
	 * @description 冻结账户
	 * @author shevliu
	 * @email shevliu@gmail.com Jul 28, 2012 6:09:25 PM
	 */
	public void doFrozen() {
		int id = getParaToInt("id");
		String content  = getPara("content");
		Db.update("update b_user set canuse=0 ,operate_reason=?,operate_time=? where id=?", content , new Date(),id);
		redirect("/driver");
	}

	/**
	 *
	 * @description 解冻账户
	 * @author shevliu
	 * @email shevliu@gmail.com Jul 28, 2012 6:09:19 PM
	 */
	public void thaw() {
		int id = getParaToInt(0);
		setAttr("id", id);
		render("driver_thaw.ftl");
	}

	/**
	 *
	 * @description 解冻账户
	 * @author shevliu
	 * @email shevliu@gmail.com Jul 28, 2012 6:09:19 PM
	 */
	public void doThaw() {
		int id = getParaToInt("id");
		String content  = getPara("content");
		Db.update("update b_user set canuse=1 ,operate_reason=?,operate_time=? where id=?", content , new Date(),id);
		redirect("/driver");
	}

	/**
	 *
	 * @description 查看用户详细资料
	 * @author shevliu
	 * @email shevliu@gmail.com Jul 28, 2012 6:58:36 PM
	 */
	public void detail() {
		int id = getParaToInt(0);
		Driver driver = Driver.dao.findById(id);
		setAttr("driver", driver);
		List<Tel> telList = Tel.dao.find("select * from tel_company where company='"+driver.getStr("license_num")+"'");
		if(telList.size() > 0){
			setAttr("tel", telList.get(0));
		}
		render("driver_detail.ftl");
	}

	/**
	 * 驾驶员地图查看
	 */
	public void map() {
		int id = getParaToInt(0);
		setAttr("driver", Driver.dao.findById(id));
		render("../map/driver_single.ftl");
	}

	public void job() {
		int id = getParaToInt(0);
		List<Record> list = Db
				.find(
						"select a.order_id,a.id as job_id , a.b_user_id , a.job_time,a.status,b.charges ,b.userarea,b.startpoint,b.endpoint,b.kilometre,b.totalmoney,b.pay_type,b.order_type,b.create_time,b.order_state from order_job a left join order_detail b on a.order_id = b.id where a.b_user_id = ? order by a.id desc",
						id);
		setAttr("list", list);
		render("driver_job_list.ftl");
	}

	public void toEditStatus() {
		setAttr("driver", Driver.dao.findById(getParaToInt()));
		render("driver_editstatus.ftl");
	}
	
	public void editStatus() {
		int id = getParaToInt("driver.id");
		int status = getParaToInt("driver.status");
		Db.update("update b_user set status = ? where id = ?",
				status, id);
		redirect("/driver");
	}
	
	public void listdistance()
	{
		setAttr("data", "");
		setAttr("status", "false");
	    renderJson();
		
		//PrintWriter out= this.getResponse().getWriter(); 
		//out.print(r.get("answer")); 
		//this.renderNull(); 
	    
	   // List<User> userList = User.dao.find("select * from user");
	   // render("userList", userList);
	}
	
	public void listLicensenum(){
		String userRole = (String)getSession().getAttribute("userRole");
		String userName = (String)getSession().getAttribute("userName");
		String sql = "";
		if(Constants.ROLE_BRAND_MANAGER.equals(userRole) || Constants.ROLE_MIDDLE_MANAGER.equals(userRole)){
			sql += " SELECT u.company ,b.companyname,b.city FROM sys_user  u LEFT JOIN tel_company b ON u.company = b.company WHERE  u.user_name = '"+userName+"'AND u.`status`=1";
		}else{
			sql = "SELECT company,companyname,city FROM tel_company";
		}
		List<Record> list = Db.find(sql);
		setAttr("record",list);
		renderJson();
	}
	
	public void loginLog(){
		String company=(String) getSession().getAttribute("company");
		String userRole = (String)getSession().getAttribute("userRole");
		String job_number = getPara("job_number");
		String real_name = getPara("real_name");
		
		String curDateStr = this.getPara("curDate");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		if(curDateStr == null){
			String curDay = sdf.format(new Date());
			setAttr("curDate", curDay);
			render("driver_login_log.ftl");
			return;
		}
		
		Date curDate = null;
		try {
			curDate = sdf.parse(curDateStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(curDate);
		
		int dayNum = getMonthLastDay(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH));
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
		String fromStr = "select b.*,";
		for(int i=1;i<=dayNum;i++){
			Calendar newCalendar = Calendar.getInstance();
			newCalendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),i);
			
			String nowDay = sdf1.format(newCalendar.getTime());
			if(i == dayNum){
				fromStr += " (select ifnull(TRUNCATE(SUM(login_total_time) /60,2),0) from b_user_login_log where login_date='"+nowDay+"' and b_user_id=b.id) as day"+i;
			}else{
				fromStr += " (select ifnull(TRUNCATE(SUM(login_total_time) /60,2),0) from b_user_login_log where login_date='"+nowDay+"' and b_user_id=b.id) as day"+i +",";
			}
		}
		String sqlTotal =  " from b_user b WHERE 1=1 ";
		
		if(Constants.ROLE_BRAND_MANAGER.equals(userRole) || Constants.ROLE_MIDDLE_MANAGER.equals(userRole)){
			sqlTotal +=" and b.license_num='"+company+"' ";
		}
		if(StringUtils.isNotBlank(job_number)){
			sqlTotal += " and b.job_number = '" + job_number +"'";
		}
		if(StringUtils.isNotBlank(real_name)){
			sqlTotal += " and b.real_name = '" + real_name +"'";
		}
		
		Page<Record> page = Db
				.paginate(
						getParaToInt(0, 1),
						10,
						fromStr,
						sqlTotal);
		
		setAttr("page", page);
		
		setAttr("curDate", curDateStr);
		setAttr("job_number", job_number);
		setAttr("real_name", real_name);

		render("driver_login_log.ftl");
	}
	
	private Date setTime(Date date, int hour, int minute, int second, int ms) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.MINUTE, minute);
		calendar.set(Calendar.SECOND, second);
		calendar.set(Calendar.HOUR_OF_DAY, hour);
		calendar.set(Calendar.MILLISECOND, ms);
		date = calendar.getTime();
		return date;
	}
	
	/**
	 * 取得当月天数
	 * */
	public int getCurrentMonthLastDay()
	{
		Calendar a = Calendar.getInstance();
		a.set(Calendar.DATE, 1);//把日期设置为当月第一天
		a.roll(Calendar.DATE, -1);//日期回滚一天，也就是最后一天
		int maxDate = a.get(Calendar.DATE);
		return maxDate;
	}

	/**
	 * 得到指定月的天数
	 * */
	public int getMonthLastDay(int year, int month)
	{
		Calendar a = Calendar.getInstance();
		a.set(Calendar.YEAR, year);
		a.set(Calendar.MONTH, month);
		a.set(Calendar.DATE, 1);//把日期设置为下个月的第一天
		a.roll(Calendar.DATE, -1);//日期回滚一天，也就是最后一天
		int maxDate = a.get(Calendar.DATE);
		return maxDate;
	}
	
	//查看在线审核列表
	public void enroll(){
		String cell_name=getPara("real_name");
		String id_card=getPara("id_card");
		String phone=getPara("phone");
		String status=getPara("status");
		
		String sql="from b_user_enroll where 1=1";
		if(StringUtils.isNotBlank(cell_name)){
			sql=sql+" and name='"+cell_name+"'";
		}
		if(StringUtils.isNotBlank(id_card)){
			sql=sql+" and id_card='"+id_card+"'";
		}
		
		if(StringUtils.isNotBlank(phone)){
			sql=sql+" and phone='"+phone+"'";
		}
		if(StringUtils.isNotBlank(status)){
			sql=sql+" and status='"+status+"'";
		}
		String city=(String) getSession().getAttribute("syscity");
		sql=sql+" and city='"+city+"'";
		
		sql=sql+" order by id desc";
		
		Page<BUserEnroll> page = BUserEnroll.dao.paginate(getParaToInt(0, 1), 10,
				"select  *", sql);
		
		List<BUserEnroll> list=new ArrayList<BUserEnroll>();
		for (BUserEnroll bUserEnroll : page.getList()) {
			BUserEnroll temp=bUserEnroll;
			String flag=bUserEnroll.getStr("flag");
			String[] flags=flag.split(";");
			String flagName="";
			for (String string : flags) {
				if("0".equals(string)){
					flagName=flagName+"代驾员;";
				}
				if("1".equals(string)){
					flagName=flagName+"配送员;";
				}
				if("2".equals(string)){
					flagName=flagName+"保镖员;";
				}
				if("3".equals(string)){
					flagName=flagName+"泊车员;";
				}
			}
			temp.put("flagName", flagName);
			list.add(temp);
		}
		
		Page<BUserEnroll> newPage=new Page<BUserEnroll>(list, page.getPageNumber(), page.getPageSize(), page.getTotalPage(), page.getTotalRow());
		setAttr("page", newPage);
		setAttr("real_name",cell_name);
		setAttr("phone",phone);
		setAttr("id_card",id_card);
		setAttr("status", status);
		
		render("driver_enroll.ftl");
	}
	
	public void enrollDetail(){
		int id=getParaToInt();
		BUserEnroll enroll=BUserEnroll.dao.findById(id);
		
		setAttr("driver", enroll);
		render("driver_enroll_index.ftl");
	}
	
	public void Ignore(){
		String id=getPara("id");
		String remark=getPara("remark");
		String userName = (String) getSession().getAttribute("userName");
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		BUserEnroll enroll=BUserEnroll.dao.findById(id);
		enroll.set("remark", remark);
		enroll.set("status", 2);
		enroll.set("status_id", userName);
		enroll.set("status_time", sdf.format(new Date()));
		
		enroll.update();
		redirect("/driver/enroll");
		
	}
	
	
	public void pass(){
		String userName = (String) getSession().getAttribute("userName");
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		BUserEnroll enroll=getModel(BUserEnroll.class);
		enroll.set("status", 1);
		enroll.set("status_id", userName);
		enroll.set("status_time", sdf.format(new Date()));
		
		String[] flags=getParaValues("post");
		String flag=StringUtils.join(flags, ";");
		
		Record rec = Db.findFirst("select id from b_user where id_card= ?",enroll.get("id_card"));
		if(rec!=null)
		{
			setAttr("code", -1);
			setAttr("msg", "身份证号已存在，重复注册");
			renderJson();
			return;
		}		
		enroll.set("flag", flag);
		enroll.update();
		
		//写入b_user表
		String password=getPara("pwd");
		Driver driver=new Driver();
		driver.put("pwd", MD5Util.MD5(password));
		String jobNumber = getPara("job_number");
		driver.put("job_number", jobNumber.toUpperCase());
		driver.put("id_card_img", enroll.getStr("id_card_img"));
		driver.put("driver_license_img", enroll.getStr("driver_license_img"));
		driver.put("phone", enroll.getStr("phone"));
		driver.put("name",enroll.getStr("name"));
		driver.put("sex",enroll.getInt("sex"));
		driver.put("hometown",enroll.getStr("hometown"));
		driver.put("driver_age",enroll.getInt("driver_age"));
		driver.put("driver_license",enroll.getStr("driver_license"));
		driver.put("age",enroll.getInt("age"));
		driver.put("license_num",getPara("compano"));
		//driver.put("company_no",getPara("compano"));
		driver.put("id_card",enroll.getStr("id_card"));
		driver.put("level", getPara("level"));
		driver.put("status",0);
		driver.put("canuse",1);
		driver.put("post",flag);
		driver.put("proportion", 30);
		int sysUserId = (Integer) getSession().getAttribute("userId");
		
		driver.put("create_user_id", sysUserId);
		driver.save();
		
		String company = (String) getSession().getAttribute("company");
		String companyname = (String) getSession().getAttribute("myCompanyName");
		String phone=enroll.getStr("phone");
		int driverId = driver.get("id");
		
		Db.update("insert into operator_log(sys_user_id,b_user_id,log_type,remarks,company,companyname,sys_user_name,create_time) values(?,?,?,?,?,?,?,?)",
				sysUserId,driverId,TypeConstant.OperatorType.DRIVER_ADD.name(),
				TypeConstant.OperatorType.DRIVER_ADD.getTypeName(),company,companyname,userName,new Date());
		
		//String content = "亲爱的"+userName+"您好，欢迎加入"+companyname+"代驾，账号:"+phone+"工号:"+jobNumber+"，密码:"+password+"。";
		String content = "欢迎你加入老兵（"+companyname+"），您的登录账号："+enroll.getStr("phone")+"，初密始密码："+password+"，请尽快上线赚钱吧！";
		if(TypeConstant.admin.endsWith(company)){
			SmsUtil.sendMessage(phone,content,company);
			
			/*String insertMessage = "insert into tel_company_message(TEL,MESSAGE,COMPANY,CREATE_TIME) values(?,?,?,?)";
			Db.update(insertMessage,phone,content,company,new java.sql.Date(Calendar.getInstance().getTime().getTime()));*/
		}else{
			Calendar calendar = Calendar.getInstance();
			calendar.set(Calendar.DAY_OF_MONTH, 1);
			calendar.set(Calendar.HOUR_OF_DAY, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.set(Calendar.MILLISECOND, 0);
			
			Calendar calendar1 = Calendar.getInstance();    
			calendar1.set(Calendar.DAY_OF_MONTH, calendar1.getActualMaximum(Calendar.DAY_OF_MONTH));
			calendar1.set(Calendar.HOUR_OF_DAY, 23);
			calendar1.set(Calendar.MINUTE, 59);
			calendar1.set(Calendar.SECOND, 0);
			calendar1.set(Calendar.MILLISECOND, 999);
			
			//String messageCountSql = "select count(*) from tel_company_message where company=? and create_time>? and create_time<=?";
			//Long count = Db.queryFirst(messageCountSql, company, calendar.getTime(), calendar1.getTime());
			
			//String companySql = "select * from tel_company where company=?";
			//Tel tel = Tel.dao.findFirst(companySql, company);
			//int messageNum = (tel.get("message_num") == null ? 0:tel.getInt("message_num"));
			//if(count < messageNum){
				SmsUtil.sendMessage(phone,content,company);
				//String insertMessage = "insert into tel_company_message(TEL,MESSAGE,COMPANY,CREATE_TIME) values(?,?,?,?)";
				//Db.update(insertMessage,phone,content,company,new java.sql.Date(Calendar.getInstance().getTime().getTime()));
			//}
		}
		setAttr("code", 0);
		renderJson();
		return;
		
	}
	
	public void drivercanpost(){
		int id=getParaToInt();
		Driver driver=Driver.dao.findById(id);
		setAttr("driver", driver);
		render("driverCanpost_edit.ftl");
	}
	
	public void editcanpost(){
		Driver driver=getModel(Driver.class);
		String[] flags=getParaValues("post");
		String flag=StringUtils.join(flags, ";");
		driver.set("canpost", flag);
		driver.update();
		redirect("/driver");
	}
}
